from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from django.conf import settings
from django.db.models import Count
from django.contrib.contenttypes.models import ContentType

from .models import Blog, BlogType
from read_statistics.utils import read_statistics_once_read
# from comment.models import Comment
# from comment.forms import CommentForm


def get_blog_list_common_data(request, blogs_all_list):
    """博客公共 分页返回博客类型及具体显示数据"""
    paginator = Paginator(blogs_all_list, settings.PAGE_COUNT)
    page_num = request.GET.get('page', 1)
    # get_page方法能自动识别信息正误，比page方法 无需判断
    page_of_blogs = paginator.get_page(page_num)
    # 获取当前页码
    current_page_num = page_of_blogs.number
    page_range = [x for x in range(current_page_num - 2, current_page_num + 3) if 0 < x <= paginator.num_pages]
    # 加上省略号
    if page_range[0] - 1 >= 2:
        page_range.insert(0, '...')
    if paginator.num_pages - page_range[-1] >= 2:
        page_range.append('...')
    # 加上首页和尾页
    if page_range[0] != 1:
        page_range.insert(0, 1)
    if page_range[-1] != paginator.num_pages:
        page_range.append(paginator.num_pages)

    # 获取日期归档的对应博客数量
    blog_dates = Blog.objects.dates('created_time', 'month', order='DESC')
    blog_dates_dict = {}
    for blog_date in blog_dates:
        blog_count = Blog.objects.filter(created_time__year=blog_date.year,
                                         created_time__month=blog_date.month).count
        blog_dates_dict[blog_date] = blog_count

    context = {}
    context['blogs'] = page_of_blogs.object_list
    context['page_of_blogs'] = page_of_blogs
    context['page_range'] = page_range

    # 获取博客分类的对应博客数量
    # annotate 拓展查询字段 blog相关联的类的小写
    context['blog_types'] = BlogType.objects.annotate(blog_count=Count('blog'))
    context['blog_dates'] = blog_dates_dict
    return context


def blog_list(request):
    """博客列表"""
    blogs_all_list = Blog.objects.all()
    context = get_blog_list_common_data(request, blogs_all_list)
    return render(request, 'blog/blog_list.html', context)


def blogs_with_type(request, blog_type_pk):
    """根据博客类型 获取类型下的所有博客"""
    blog_type = get_object_or_404(BlogType, pk=blog_type_pk)
    blogs_all_list = Blog.objects.filter(blog_type=blog_type)
    context = get_blog_list_common_data(request, blogs_all_list)
    context['blog_type'] = blog_type
    return render(request, 'blog/blogs_with_type.html', context)


def blogs_with_date(request, year, month):
    """根据时间归档 获取某时间内创建的所有博客"""
    blogs_all_list = Blog.objects.filter(created_time__year=year, created_time__month=month)
    context = get_blog_list_common_data(request, blogs_all_list)
    context['blog_with_date'] = "{0}年{1}月".format(year, month)
    return render(request, 'blog/blogs_with_date.html', context)


def blog_detail(request, blog_pk):
    """博客详情"""
    blog = get_object_or_404(Blog, pk=blog_pk)
    read_cookie_key = read_statistics_once_read(request, blog)
    # 值也是blog，但类型是<class 'django.contrib.contenttypes.models.ContentType'>
    # blog_content_type = ContentType.objects.get_for_model(blog)
    # 用简单文本标签替代此方法
    # comments = Comment.objects.filter(content_type=blog_content_type, object_id=blog.pk, parent=None)

    context = {}
    context['blog'] = blog
    # 获取上一篇博客
    context['previous_blog'] = Blog.objects.filter(created_time__gt=blog.created_time).last()
    # 获取下一篇博客
    context['next_blog'] = Blog.objects.filter(created_time__lt=blog.created_time).first()
    # 获取该博客的所有评论(用简单文本标签替代此方法)
    # context['comments'] = comments.order_by('-comment_time')
    # 用简单文本标签替代此方法
    # 获取Form渲染的评论
    # data = {}
    # data['content_type'] = blog_content_type.model
    # data['object_id'] = blog_pk
    # data['reply_comment_id'] = 0
    # 对form进行初始化操作
    # context['comment_form'] = CommentForm(initial=data)
    response = render(request, 'blog/blog_detail.html', context)
    # 阅读cookie标志
    response.set_cookie(read_cookie_key, 'true')
    return response
